package com.dht.xiao.jianye.dayin.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.dayin.ErrorOrMsg;
import com.dht.xiao.jianye.dayin.Event;
import com.dht.xiao.jianye.dayin.MyApplication;
import com.dht.xiao.jianye.dayin.PrinterManager;
import com.dht.xiao.jianye.dayin.util.ToastUtil;
import com.dht.xiao.jianye.dayin.util.WifiSharePreference;
import com.jolimark.printerlib.DeviceInfo;
import com.jolimark.printerlib.RemotePrinter;
import com.jolimark.printerlib.VAR.TransType;
import com.jolimark.printerlib.util.WifiPrinterIPUtil.RefleshHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class WifiSettingFragment extends Fragment implements View.OnClickListener {
	private Activity activity = null;
	private MyApplication myapplication;
	private PrinterManager printerManager = null;
	private ProgressDialog m_pDialog; // 进度条
	private EditText et_ip, et_port;
	private Button btn_wifi_search, btn_save, btn_wifisetting;
	private ListView lv_wifilist;
	private List<DeviceInfo> wifiList = null;// wifi列表
	private ArrayAdapter<String> wifiDevicesArrayAdapters = null; // 已经搜索到的设备列表
	private WifiSharePreference wifiSharePreference = null;// 保存wifi配置信息
	private String eIP = "10.10.10.1"; // 默认IP
	private String ePort = "9100"; // 默认端口号
	private int searchTime = 24;// 查找设备时间 24秒

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			m_pDialog.dismiss();
			switch (msg.what) {
			case ErrorOrMsg.DEVICE_FOUND:
				DeviceInfo deviceInfo = wifiList.get(wifiList.size()-1);
				wifiDevicesArrayAdapters.add("Name: "+deviceInfo.type + "\nMac: " + deviceInfo.mac);
				wifiDevicesArrayAdapters.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = activity;
		myapplication = (MyApplication) getActivity().getApplication();
        printerManager = myapplication.getPrinterManager();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// 注册EventBus
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_setting_wifi, null);
		et_ip = (EditText) view.findViewById(R.id.et_ip);
		et_port = (EditText) view.findViewById(R.id.et_port);
		btn_wifi_search = (Button) view.findViewById(R.id.btn_wifi_search);
		btn_save = (Button) view.findViewById(R.id.btn_connect);
		btn_wifisetting = (Button) view.findViewById(R.id.btn_wifisetting);
		lv_wifilist = (ListView) view.findViewById(R.id.lv_wifilist);

		btn_wifi_search.setOnClickListener(this);
		btn_save.setOnClickListener(this);
		btn_wifisetting.setOnClickListener(this);

		if (printerManager.isConnected()) {
			TransType ty = printerManager.getTransType();
			if (ty == TransType.TRANS_WIFI) {
				if (printerManager.isConnected()) {
					btn_save.setText(getString(R.string.connect_exist));
					btn_save.setTextColor(Color.GRAY);
					btn_save.setEnabled(false);
					btn_wifi_search.setTextColor(Color.GRAY);
					btn_wifi_search.setEnabled(false);
				}
				String path = printerManager.getAddress();
				String[] pathData = path.split(":");
				et_ip.setText(pathData[0]);
				et_port.setText(pathData[1]);
			}
		}

		// 显示连接进度对话框
		m_pDialog = new ProgressDialog(activity);
		m_pDialog.setMessage(getResources().getString(R.string.connecting));
		m_pDialog.setIndeterminate(false);
		m_pDialog.setCanceledOnTouchOutside(false);

		wifiList = new ArrayList<DeviceInfo>();
		
		wifiDevicesArrayAdapters = new ArrayAdapter<String>(getActivity(), R.layout.item_device);
		lv_wifilist.setAdapter(wifiDevicesArrayAdapters);
		
		// 设备点击事件
		lv_wifilist.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				RemotePrinter.cancelGetWifiPrinterIP();// 取消搜索
				et_ip.setText(wifiList.get(position).ip); // 设置IP

				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
				builder.setTitle(getString(R.string.select_connect_type));
				builder.setMessage(getString(R.string.connect_dialog_message));
				builder.setPositiveButton(getString(R.string.open), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						printerManager.setOpenTwoWayFlag(true);
						eIP = et_ip.getText().toString().trim(); // 获取IP
						ePort = et_port.getText().toString().trim(); // 获取端口号
						wifiConnect(eIP, ePort);
					}
				});
				builder.setNegativeButton(getString(R.string.no_open), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						printerManager.setOpenTwoWayFlag(false);
						eIP = et_ip.getText().toString().trim(); // 获取IP
						ePort = et_port.getText().toString().trim(); // 获取端口号
						wifiConnect(eIP, ePort);
					}
				});
				builder.show();
			}
		});

		initWIFI();
		return view;
	}

	/**
	 * 初始化wifi配置信息，从文件中读取
	 */
	private void initWIFI() {
		wifiSharePreference = new WifiSharePreference(activity);
		String ip = wifiSharePreference.getIP();
		if (ip != "") {
			et_ip.setText(ip);
		} else {
			// 设置默认IP值
			et_ip.setText(eIP);
		}
		String port = wifiSharePreference.getPort();
		if (port != "") {
			et_port.setText(port);
		} else {
			// 设置默认端口号
			et_port.setText(ePort);
		}
		wifiSharePreference = null;
	}

	// 保存wifi配置IP、port
	private void saveWIFI(String ip, String port) {
		wifiSharePreference = new WifiSharePreference(activity);
		wifiSharePreference.setIP(ip);
		wifiSharePreference.setPort(port);
		wifiSharePreference = null;
	}

	@Override
	public void onDestroy() {
		RemotePrinter.cancelGetWifiPrinterIP();//关闭搜索
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_wifisetting: // 打开WIFI设置
			startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0x123);
			break;
		case R.id.btn_connect: // 连接打印机
			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setTitle(getString(R.string.select_connect_type));
			builder.setMessage(getString(R.string.connect_dialog_message));
			builder.setPositiveButton(getString(R.string.open), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					printerManager.setOpenTwoWayFlag(true);
					eIP = et_ip.getText().toString().trim(); // 获取IP
					ePort = et_port.getText().toString().trim(); // 获取端口号
					wifiConnect(eIP, ePort);
				}
			});
			builder.setNegativeButton(getString(R.string.no_open), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					printerManager.setOpenTwoWayFlag(false);
					eIP = et_ip.getText().toString().trim(); // 获取IP
					ePort = et_port.getText().toString().trim(); // 获取端口号
					wifiConnect(eIP, ePort);
				}
			});
			builder.show();

			break;
		case R.id.btn_wifi_search: // 搜索打印机
			wifiDevicesArrayAdapters.clear();
			wifiList.clear();// 清空列表并刷新
			wifiDevicesArrayAdapters.notifyDataSetChanged();
			// 搜索wifi设备IP，时间24秒
			RemotePrinter.getWifiPrinterIP(searchTime, new RefleshHandler() {
				@Override
				public void searchFinish() {

				}

				@Override
						public void deviceFound(DeviceInfo deviceInfo) {
							if (!(wifiList.contains(deviceInfo))) {
						wifiList.add(deviceInfo);
						mHandler.sendEmptyMessage(ErrorOrMsg.DEVICE_FOUND);
					}
				}
			});
			break;
		}
	}

	private void wifiConnect(String eIP2, String ePort2) {
		m_pDialog.show();
		// 初始化printerManager的连接信息
		printerManager.initRemotePrinter(TransType.TRANS_WIFI, eIP2 + ":" + ePort2);
		new Thread() {
			public void run() {
				// 建立连接
				printerManager.connect();
			}
		}.start();
	}
	@Subscribe(threadMode = ThreadMode.MAIN)
	// 接收连接事件信息
	public void onEventMainThread(Event connectEvent) {
		m_pDialog.dismiss();
		switch (connectEvent.msg) {
		case ErrorOrMsg.CONNECT_SUCCESSED:
			Log.d("tag", "-------------------------连接成功");

			btn_wifi_search.setText(getString(R.string.wifi_search));
			saveWIFI(eIP, ePort);// 保存wifi设置，方便下次使用

			ToastUtil.show(activity, R.string.test_connect_success);
			printerManager.close();
			break;
		case ErrorOrMsg.CONNECT_FAILED:
			Log.d("tag", "-------------------------连接失败");
//			ToastUtil.show(activity, R.string.connect_faile);
			printerManager.resetConfig();
			break;
		case ErrorOrMsg.CONNECT_EXIST:
			Log.d("tag", "-------------------------已连接");
			ToastUtil.show(activity, R.string.connect_exist);
			break;
		case ErrorOrMsg.CONFIG_NULL:
			Log.d("tag", "-------------------------空");
			ToastUtil.show(activity, R.string.config_null);
			break;
		case ErrorOrMsg.UNCONNECT:
			Log.d("tag", "-------------------------无连接");
			ToastUtil.show(activity, R.string.no_connect);
			break;

		}
	}
}
